package cscie160.project;

import java.rmi.Remote;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.Map;
import java.util.TreeMap;

/**
 * ATMServer side representation of an ATM
 */
public class BankImplementation extends UnicastRemoteObject implements Bank
{
    /** Store a bunch of accounts, each with its own unique ID  */
    private Map<Integer, Account> accountMap;

    public BankImplementation() throws RemoteException
    {
        accountMap = new TreeMap<Integer, Account>();
        createAccount(0000001, 0);
        createAccount(0000002, 100);
        createAccount(0000003, 500);
    }

     public Account getAccount(int accountNumber) throws RemoteException
    {
        return accountMap.get(Integer.valueOf(accountNumber));
    }

    /**
     * Creates a new account with the given account number, with an amount of money equal to the starting balance.
     * The account cannot have the same number as an existing account.
     * @param accountNumber  The number of the account
     * @param startingBalance The starting balance of the account
     * @return True if the account was successfully created, false if the account was not created.
     */
    private boolean createAccount(int accountNumber, float startingBalance)
    {
        try
        {
            // First check if there's already an account with that number
            if (getAccount(accountNumber) != null)
            {
                return false;
            }

            // Don't allow negative starting balances
            if (startingBalance < 0)
            {
                return false;
            }
            AccountImplementation newAccount = new AccountImplementation();
            newAccount.deposit(startingBalance);
            accountMap.put(Integer.valueOf(accountNumber), newAccount);
            return true;
        } catch (RemoteException re)
        {
            re.printStackTrace();
            return false;
        }
    }
}
